package com.ym.wcp.framework.handler;

import com.ym.wcp.framework.annotation.Disable;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

public class MyRequestMappingHandler extends RequestMappingHandlerMapping {

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        Disable deprecated = handlerType.getAnnotation(Disable.class);
        if (deprecated != null && deprecated.target() == handlerType) {
            return null;
        }
        RequestMappingInfo info = getRequestMappingInfo(method);
        if (info != null) {
            RequestMappingInfo typeInfo = getRequestMappingInfo(handlerType);
            if (typeInfo != null) {
                info = typeInfo.combine(info);
            }
        }
        return info;
    }

    private RequestMappingInfo getRequestMappingInfo(AnnotatedElement element) {
        RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
        Disable deprecated = AnnotatedElementUtils.findMergedAnnotation(element, Disable.class);
        if (deprecated != null) {
            return null;
        }
        RequestCondition<?> condition = element instanceof Class ? this.getCustomTypeCondition((Class<?>) element) : this.getCustomMethodCondition((Method) element);
        return requestMapping != null ? this.createRequestMappingInfo(requestMapping, condition) : null;
    }
}
